#pragma once

#include <string>
#include <cstring>
#include <cerrno>

#include <fcntl.h>

using namespace std;

enum class CommonError
{
    OK = 0,
    SOCKET_ERROR, // socket创建失败
    BIND_ERROR,   // bind失败
    SENDTO_ERROR,
    RECVFROM_ERROR,
    SEND_ERROR,
    RECV_ERROR
};

void FdSetNonBlock(int fd) // 把fd设置为非阻塞
{
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        perror("FdSetNoBlocking:");
        return;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}

bool Partition(const string &str, const string &sep, string &left, string &right) // 分割函数，以sep为分割符分割str
{
    int pos = str.find(sep);
    if (pos != string::npos)
    {
        left = str.substr(0, pos);
        right = str.substr(pos + sep.size());
        return true;
    }
    return false;
}

string ErrortoString(CommonError e)
{
    string s;
    switch (e)
    {
    case CommonError::SOCKET_ERROR:
        s = "deadly: socket_error";
        break;
    case CommonError::BIND_ERROR:
        s = "deadly: bind_error";
        break;
    case CommonError::SENDTO_ERROR:
        s = "error: sendto_error";
        break;
    case CommonError::RECVFROM_ERROR:
        s = "error: recvfrom_error";
        break;
    default:
        s = "deadly unknown error"; // 未知错误
        break;
    }
    return s;
}
